package com.ptt.sqmonmobile;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.GPSTracker;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class GPSActivity extends Activity {

	TextView textview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gps);

		// check if GPS enabled
		GPSTracker gpsTracker = new GPSTracker(this);
//		gpsTracker.latitude = 13.7883673d;
//		gpsTracker.longitude = 100.5508532d;

		if (gpsTracker.canGetLocation()) {
			String stringLatitude = String.valueOf(gpsTracker.latitude);
			textview = (TextView) findViewById(R.id.fieldLatitude);
			textview.setText(stringLatitude);

			String stringLongitude = String.valueOf(gpsTracker.longitude);
			textview = (TextView) findViewById(R.id.fieldLongitude);
			textview.setText(stringLongitude);
			
			//Location mLocation = new Location(LocationManager.GPS_PROVIDER);
			 (new GetAddressTask(this)).execute(gpsTracker.getLocation());

//			String country = gpsTracker.getCountryName(this);
//			textview = (TextView) findViewById(R.id.fieldCountry);
//			textview.setText(country);
//
//			String city = gpsTracker.getLocality(this);
//			textview = (TextView) findViewById(R.id.fieldCity);
//			textview.setText(city);
//
//			String postalCode = gpsTracker.getPostalCode(this);
//			textview = (TextView) findViewById(R.id.fieldPostalCode);
//			textview.setText(postalCode);
//
//			String addressLine = gpsTracker.getAddressLine(this);
//			textview = (TextView) findViewById(R.id.fieldAddressLine);
//			textview.setText(addressLine);
			final double lat = gpsTracker.latitude;
			final double lon = gpsTracker.longitude;

			textview = (TextView) findViewById(R.id.current_location);
			textview.setText("\"" + lat + " \"" + lon);
			textview.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent it = new Intent(getApplicationContext(),
							GooglemapActivity.class);
					it.putExtra(AppUtil.LATITUDE, lat);
					it.putExtra(AppUtil.LONGTITUDE, lon);
					startActivity(it);
				}
			});

		} else {
			// can't get location
			// GPS or Network is not enabled
			// Ask user to enable GPS/network in settings
			gpsTracker.showSettingsAlert();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.g, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private class GetAddressTask extends AsyncTask<Location, Void, String> {
		Context mContext;
		public GetAddressTask(Context context) {
			super();
			mContext = context;
		}

		/**
		 * Get a Geocoder instance, get the latitude and longitude look up the
		 * address, and return it
		 * 
		 * @params params One or more Location objects
		 * @return A string containing the address of the current location, or
		 *         an empty string if no address can be found, or an error
		 *         message
		 */
		@Override
		protected String doInBackground(Location... params) {
			Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
			// Get the current location from the input parameter list
			Location loc = params[0];
			// Create a list to contain the result address
			List<Address> addresses = null;
			try {
				/*
				 * Return 1 address.
				 */
				addresses = geocoder.getFromLocation(13.7883673d,
						100.5508532d, 1);
			} catch (IOException e1) {
				Log.e("LocationSampleActivity",
						"IO Exception in getFromLocation()");
				e1.printStackTrace();
				return ("IO Exception trying to get address");
			} catch (IllegalArgumentException e2) {
				// Error message to post in the log
				String errorString = "Illegal arguments "
						+ Double.toString(13.7883673d) + " , "
						+ Double.toString(100.5508532d)
						+ " passed to address service";
				Log.e("LocationSampleActivity", errorString);
				e2.printStackTrace();
				return errorString;
			}
			// If the reverse geocode returned an address
			if (addresses != null && addresses.size() > 0) {
				// Get the first address
				Address address = addresses.get(0);
				/*
				 * Format the first line of address (if available), city, and
				 * country name.
				 */
				String addressText = String.format(
						"%s, %s, %s",
						// If there's a street address, add it
						address.getMaxAddressLineIndex() > 0 ? address
								.getAddressLine(0) : "",
						// Locality is usually a city
						address.getLocality(),
						// The country of the address
						address.getCountryName());
				// Return the text
				return addressText;
			} else {
				return "No address found";
			}
		}
		
		
		
		
		
		
		
		 @Override
	        protected void onPostExecute(String address) {
	         
	            // Display the results of the lookup.
			 textview.setText(address);
	        }


	}

}
